import React from 'react';
import {injectIntl, language} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Modal, Alert} from 'antd';
import TextInput from 'Shared/components/TextInput';
import DateRangePicker from 'Shared/components/DateRangePicker';
import {PERMISSION} from './constants';
import {FORM_OPTIONS, FORM_ROW_OPTIONS} from '../constants';
import WrappedSelect from '../common/WrappedSelect';
import {hasPermissions} from './utils';
import {baseDataStatus, orderUnmetReasonType} from '../Enum';
const ButtonGroup = Button.Group;
const FormItem = Form.Item;
const EMPTY_ARRAY = [];
const autosize = {minRows: 1};
import {addInfo} from './api';
import styles from './style.css';
/*eslint-disable  react/prefer-stateless-function*/
class QueryPanel extends React.PureComponent {
    state = {
        loading: false,
        showPanel: false,
        isValidate: false,
        name: '',
        brandId: '',
        remark: '',
    }

    handleFilterChange = (value, name) => {
        this.setState({
            [name]: value
        });
    }


    onCancel = () => {
        this.setState({
            brandId: '',
            name: '',
            type: undefined,
            remark: '',
            showPanel: false,
            isValidate: false,
        });
    }
    
    onClickAdd = () => {
        this.setState({
            showPanel: true
        });
    }

    onSubmit = () => {
        if(!this.state.name || !this.state.type)
            return this.setState({
                isValidate: true,
            });
        
        this.setState({
            loading: true
        });
        return addInfo({
            brandId: this.state.brandId,
            name: this.state.name,
            type: this.state.type,
            remark: this.state.remark
        }).then(res => {
            this.setState({
                loading: false,
            });
            if(res.ok) {
                this.onCancel();
                this.props.querySearch();
            }
        });
    }

    render() {
        const operations = [];
        const otherBtns = [];
        const msgs = [];
        if(!this.state.brandId)
            msgs.push(this.props.intl.formatMessage({
                id: 'queryPanel.alert.brandId',
                defaultMessage: '品牌'
            }));
        if(!this.state.name)
            msgs.push(this.props.intl.formatMessage({
                id: 'queryPanel.alert.name',
                defaultMessage: '名称'
            }));
        if(!this.state.type)
            msgs.push(this.props.intl.formatMessage({
                id: 'queryPanel.alert.type',
                defaultMessage: '类型'
            }));
        const alertMessage = msgs.length ? `${msgs.join(
            this.props.intl.formatMessage({
                id: 'queryPanel.comma',
                defaultMessage: '、'
            })
        )}${this.props.intl.formatMessage({
            id: 'queryPanel.notEmpty',
            defaultMessage: '不能为空'
        })}` : '';
        if(hasPermissions(this.props.permissions, PERMISSION.add))
            operations.push(
                <Button key="add" type="primary" onClick={this.onClickAdd}>
                    {this.props.intl.formatMessage({
                        id: 'queryPanel.btn.add',
                        defaultMessage: '新增'
                    })}
                </Button>
            );

        return (
            <div>
                <Modal
                    title={this.props.intl.formatMessage({
                        id: 'queryPanel.modale.title',
                        defaultMessage: '新增'
                    })}
                    width="60%"
                    maskClosable={false}
                    onOk={this.onSubmit}
                    destroyOnClose={true}
                    confirmLoading={this.state.loading}
                    visible={this.state.showPanel}
                    onCancel={this.onCancel}>
                    <Form className="form-standard">
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    validateStatus={this.state.isValidate && !this.state.brandId ? 'error' : null}
                                    required
                                    label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.brandId',
                                        defaultMessage: '品牌'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <WrappedSelect
                                        name="brandId"
                                        allowClear
                                        value={this.state.brandId}
                                        options={this.props.brands}
                                        onChange={this.handleFilterChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    validateStatus={this.state.isValidate && !this.state.name ? 'error' : null}
                                    required
                                    label={this.props.intl.formatMessage({
                                        id: 'queryPanel.add.form.name',
                                        defaultMessage: '名称'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <TextInput name="name"
                                        value={this.state.name} onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'queryPanel.add.form.type',
                                        defaultMessage: '类型'
                                    })}
                                    {...FORM_OPTIONS.item}
                                    validateStatus={this.state.isValidate && !this.state.type ? 'error' : null}
                                    required>
                                    <WrappedSelect
                                        name="type"
                                        value={this.state.type}
                                        options={orderUnmetReasonType.toList(language)}
                                        onChange={this.handleFilterChange} />
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.add.form.remark',
                                    defaultMessage: '备注'
                                })}
                                {...FORM_ROW_OPTIONS.item}>
                                <TextInput type="textarea" name="remark" autosize={autosize}
                                    value={this.state.remark} onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Row>
                        {this.state.isValidate && alertMessage && <Alert message={alertMessage} className={styles.alertMargin} type="warning" showIcon />}
                    </Form>
                </Modal>
                <Form className="form-standard">
                    <Row>
                        {this.props.brands.length > 1 ? <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.brandId',
                                    defaultMessage: '品牌'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    name="brandId"
                                    allowClear
                                    value={this.props.conditions.brandId}
                                    options={this.props.brands}
                                    onChange={this.props.onConditionsChange} />
                            </FormItem>
                        </Col> : null}
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.status',
                                    defaultMessage: '状态'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="status"
                                    value={this.props.conditions.status}
                                    options={baseDataStatus.toList(language)}
                                    onChange={this.props.onConditionsChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.createTime',
                                    defaultMessage: '创建时间'
                                })}
                                {...FORM_OPTIONS.item}>
                                <DateRangePicker name="createTime" value={this.props.conditions.createTime}
                                    onChange={this.props.onConditionsChange} />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row className="operation-buttons">
                        <Col span={6}>
                            <Button
                                key="query"
                                type="primary"
                                onClick={this.props.querySearch}
                                loading={this.props.loading}>
                                {this.props.intl.formatMessage({
                                    id: 'queryPanel.btn.query',
                                    defaultMessage: '查询'
                                })}
                            </Button>
                            <Button key="clear" onClick={this.props.onClickReset}>
                                {this.props.intl.formatMessage({
                                    id: 'queryPanel.btn.reset',
                                    defaultMessage: '重置'
                                })}
                            </Button>
                        </Col>
                        <Col span={18} className="col-align-right">
                            <ButtonGroup>{otherBtns}</ButtonGroup>
                            {operations}
                        </Col>
                    </Row>
                </Form>
            </div>
        );
    }
}

QueryPanel.propTypes = {
    brands: PropTypes.array.isRequired,
    conditions: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    querySearch: PropTypes.func.isRequired,
    onClickReset: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onConditionsPressEnter: PropTypes.func.isRequired,
    intl: PropTypes.object
};
import {connect} from 'react-redux';
import {saveQueryCondition, querySearch, resetQueryPanel} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const getBrandsData = createSelector(
    state => state.getIn(['page', 'domainData', 'brands', 'data']),
    initData => {
        const data = initData.toJS() || EMPTY_ARRAY;
        return data.map(item => ({
            text: item.name,
            value: item.id
        }));
    }
);
const mapStateToProps = state => ({
    conditions: getConditions(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    permissions: getPermissions(state),
    brands: getBrandsData(state),
});

const mapDispatchToProps = dispatch => ({
    onConditionsChange: (value, name) => dispatch(saveQueryCondition(name, value)),
    onConditionsPressEnter: (value, name) => {
        dispatch(saveQueryCondition(name, value));
        dispatch(querySearch());
    },
    querySearch: () => dispatch(querySearch()),
    onClickReset: () => dispatch(resetQueryPanel()),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(QueryPanel));
